package cn.jzq.kotoba.modules.redis.api.list;

import cn.hutool.core.date.DateUtil;
import cn.jzq.kotoba.common.consts.CommonConst;
import cn.jzq.kotoba.common.consts.redis.ReadNoteRedisConst;
import cn.jzq.kotoba.common.util.R;
import cn.jzq.kotoba.modules.sharding.mapper.ReadNoteMapper;
import cn.jzq.kotoba.modules.sharding.model.entity.ReadNote;
import cn.jzq.kotoba.modules.sharding.model.entity.Student;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

import static cn.jzq.kotoba.common.consts.redis.ReadNoteRedisConst.READ_NOTE_LIST_NAME;
import static cn.jzq.kotoba.common.consts.redis.ReadNoteRedisConst.STU_READ_NOTE;

/**
 * 使用redis list数据结构实现分页
 * 依赖   <dependency>
 * <groupId>org.springframework.boot</groupId>
 * <artifactId>spring-boot-starter-data-redis</artifactId>
 * </dependency>
 *
 * @author jzq
 * @date 2018-11-23
 */
@RestController
@RequestMapping("/redis")
public class RedisListDemo {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private ReadNoteMapper readNoteMapper;

    @ApiOperation(value = "新增阅读笔记")
    @PostMapping("/readNote")
    public R postReadNote(@RequestBody ReadNote readNote) {
        readNote.setDelFlag(CommonConst.STATUS_NORMAL);
        readNote.setCreateTime(DateUtil.date());
        readNoteMapper.insert(readNote);
        redisTemplate.opsForValue().set(READ_NOTE_LIST_NAME + readNote.getId(), readNote);
        redisTemplate.opsForList().leftPush(STU_READ_NOTE + readNote.getStuId(), readNote.getId());
        return R.ok();
    }

    @ApiOperation(value = "分页获取学生的阅读笔记")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "stuId", value = "学生id"),
            @ApiImplicitParam(name = "page", value = "当前页码"),
            @ApiImplicitParam(name = "limit", value = "每页条数")
    })
    @GetMapping("/readNote")
    @SuppressWarnings("unchecked")
    public R readNotePage(Long stuId, Integer page, Integer limit) {
        Integer offset = (page - 1) * limit;
        List<Object> readNoteIds = redisTemplate.opsForList().range(STU_READ_NOTE + stuId, offset, offset + limit);
        if (readNoteIds != null) {
            List<String> readNoteStrIds = new ArrayList<>();
            readNoteIds.forEach(readNoteId -> readNoteStrIds.add(READ_NOTE_LIST_NAME + readNoteId.toString()));
            List<Object> list = redisTemplate.opsForValue().multiGet(readNoteStrIds);
            return R.ok(list);
        }
        return R.ok(new ArrayList<>());
    }
}
